package com.lghdb.driver_client;

import android.app.Activity;
import android.app.Dialog;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.lghdb.driver_client.util.User;
import com.lghdb.driver_client.util.Utils;

import java.util.ArrayList;

public class LoginActivity extends Activity
    implements View.OnClickListener,
        AdapterView.OnItemClickListener,
        PopupWindow.OnDismissListener{

    private EditText mIdEditText; //用户名
    private EditText mPwdEditText;
    private ImageView mMoreUser;
    private Button mLoginButton;
    private ImageView mLoginMoreUserView;
    private LinearLayout mLoginLinearLayout;
    private LinearLayout mUserIdLinearLayout;
    private Animation mTranslate;
    private Dialog mLoginingDlg;

    private String mIdString;
    private String mPwdString;
    private ArrayList<User> mUsers;
    private ListView mUserIdListView;
    private UserApter mAdapter;
    private PopupWindow mPop;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        initView();
        setListener();
        this.mLoginLinearLayout.startAnimation(mTranslate);

        //加载历史用户
        mUsers = Utils.getUserList(LoginActivity.this);
        if (mUsers.size() > 0){
            mIdEditText.setText(mUsers.get(0).getId());
            mPwdEditText.setText(mUsers.get(0).getPwd());
        }
        LinearLayout parent = (LinearLayout)getLayoutInflater()
                .inflate(R.layout.userifo_listview, null);
        mUserIdListView = parent.findViewById(android.R.id.list);
        parent.removeView(mUserIdListView);
        mUserIdListView.setOnItemClickListener(this);
        mAdapter = new UserApter(mUsers);
        mUserIdListView.setAdapter(mAdapter);
    }

    private void initView(){
        mIdEditText = findViewById(R.id.login_edtId);
        mPwdEditText = findViewById(R.id.login_edtPwd);
        mMoreUser = findViewById(R.id.login_more_user);
        mLoginButton =  findViewById(R.id.login_btnLogin);
        mLoginMoreUserView =  findViewById(R.id.login_more_user);
        mLoginLinearLayout = findViewById(R.id.login_linearLayout);
        mUserIdLinearLayout = findViewById(R.id.userId_LinearLayout);
        mTranslate = AnimationUtils.loadAnimation(this, R.anim.my_translate);
        initLoginingDlg();
    }

    private void initLoginingDlg() {

        mLoginingDlg = new Dialog(this, R.style.loginingDlg);
        mLoginingDlg.setContentView(R.layout.logining_dlg);

        Window window = mLoginingDlg.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();


        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int cxScreen = dm.widthPixels;
        int cyScreen = dm.heightPixels;

        int height = (int) getResources().getDimension(
                R.dimen.loginingdlg_height);
        int lrMargin = (int) getResources().getDimension(
                R.dimen.loginingdlg_lr_margin);
        int topMargin = (int) getResources().getDimension(
                R.dimen.loginingdlg_top_margin);

        params.y = (-(cyScreen - height) / 2) + topMargin;

        params.width = cxScreen;
        params.height = height;

        mLoginingDlg.setCanceledOnTouchOutside(true);
    }

    public void initPop() {
        int width = mUserIdLinearLayout.getWidth() - 4;
        int height = LayoutParams.WRAP_CONTENT;
        mPop = new PopupWindow(mUserIdListView, width, height, true);
        mPop.setOnDismissListener(this);

        mPop.setBackgroundDrawable(new ColorDrawable(0xffffffff));

    }
    private void setListener(){
        this.mIdEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                mIdString = charSequence.toString();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        this.mPwdEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                mPwdString = charSequence.toString();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        this.mLoginButton.setOnClickListener(this);
        this.mLoginMoreUserView.setOnClickListener(this);
    }

    class UserApter extends ArrayAdapter<User>{

        public UserApter(ArrayList<User> users){
            super(LoginActivity.this,0, users);
        }

        public View getView(final int position, View convertView,
                            ViewGroup parent) {
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(
                        R.layout.listview_item, null);
            }

            TextView userIdText =  convertView
                    .findViewById(R.id.listview_userid);
            userIdText.setText(getItem(position).getId());

            ImageView deleteUser = convertView
                    .findViewById(R.id.login_delete_user);
            deleteUser.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (getItem(position).getId().equals(mIdString)) {
                        mIdString = "";
                        mPwdString = "";
                        mIdEditText.setText(mIdString);
                        mPwdEditText.setText(mPwdString);
                    }
                    mUsers.remove(getItem(position));
                    mAdapter.notifyDataSetChanged();
                }
            });
            return convertView;
        }
    }

    private void showLoginingDlg() {
        if (mLoginingDlg != null)
            mLoginingDlg.show();
    }

    private void closeLoginingDlg() {
        if (mLoginingDlg != null && mLoginingDlg.isShowing())
            mLoginingDlg.dismiss();
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_btnLogin:
                if (mIdString == null || mIdString.equals("")) {
                    Toast.makeText(LoginActivity.this,
                            "请正确填写用户名",
                            Toast.LENGTH_SHORT)
                            .show();
                } else if (mPwdString == null || mPwdString.equals("")) {
                    Toast.makeText(LoginActivity.this, "请填写密码", Toast.LENGTH_SHORT)
                            .show();
                } else {
                    showLoginingDlg();
                    boolean mIsSave = true;
                    try {
                        for (User user : mUsers) {
                            if (user.getId().equals(mIdString)) {
                                mIsSave = false;
                                break;
                            }
                        }
                        if (mIsSave) {
                            User user = new User(mIdString, mPwdString);
                            mUsers.add(user);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    closeLoginingDlg();
                    Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            case R.id.login_more_user:
                if (mPop == null) {
                    initPop();
                }
                if (!mPop.isShowing() && mUsers.size() > 0) {
                    mMoreUser.setImageResource(R.mipmap.login_more_down);
                    mPop.showAsDropDown(mUserIdLinearLayout, 2, 1);
                }
                break;
            default:
                break;
        }

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        mIdEditText.setText(mUsers.get(position).getId());
        mPwdEditText.setText(mUsers.get(position).getPwd());
        mPop.dismiss();
    }

    @Override
    public void onDismiss() {
        mMoreUser.setImageResource(R.mipmap.login_more_up);
    }

    @Override
    public void onPause() {
        super.onPause();
        try {
            Utils.saveUserList(LoginActivity.this, mUsers);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
